package com.hmall.common.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;


@RequiredArgsConstructor
@Slf4j
@Component
public class RabbitMqHelper {

    private final RabbitTemplate rabbitTemplate;

    public void sendMessage(String exchange, String routingKey, Object msg){
        rabbitTemplate.convertAndSend(exchange, routingKey, msg);
    }

    public void sendDelayMessage(String exchange, String routingKey, Object msg, int delay){
        rabbitTemplate.convertAndSend(exchange, routingKey, msg, message -> {
            message.getMessageProperties().setDelay(delay);
            return message;
        });
    }

    public void sendMessageWithConfirm(String exchange, String routingKey, Object msg, int maxRetries){
        int retry = 0;
        boolean success = false;

        while (!success && retry < maxRetries) {
            try {
                rabbitTemplate.convertAndSend(exchange, routingKey, msg);
                success = true;
            } catch (Exception e) {
                retry++;
                if (retry >= maxRetries) {
                    log.error("消息发送失败，已达最大重试次数", e);
                    throw new RuntimeException("消息发送失败", e);
                }
                try {
                    Thread.sleep(1000); // 每次重试间隔1秒
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}
